<!--
        Copyright (c) 2023, LXMS (lxinet.cn).

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

     http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
-->
<template>
  <a-row>
    <a-col :span="5">
      <div class="lPanelBox">
        <a-input-search
            style="margin-bottom: 2px"
            placeholder="搜索"
            @change="searchInit"
            :allowClear="true"
            v-model:value="searchPerson"
        ></a-input-search>
        <a-tree class="treeBox"
                v-model:selectedKeys="selectedKeys"
                v-model:checkedKeys="checkedKeys"
                ref="tree"
                defaultExpandAll="true"
                v-if="currentTree.length > 0"
                :fieldNames="fieldNames"
                :tree-data="currentTree"
                autoExpandParent
                @select="onSelect"
        />

      </div>
    </a-col>
    <a-col :span="19">
      <div class="rPanelBox">
        <slot name="panel"></slot>
      </div>
    </a-col>
  </a-row>
</template>

<script>
  export default {
    props: {
      url:{
        type:String,
        default:""
      },
      params:{
        type:Object,
        default:{}
      },
      autoLoad: {
        type: Boolean,
        default: true,
      },
      fieldNames:{
        type:Object,
        default:()=>{
          return {
            children:'children', title:'name', key:'id'
          }
        }
      },
      title:{
        type:String,
        default:"",
        require:true
      },
      key:{
        type:String,
        default:"",
        require: true
      },
      defaultSelect: {
        type: Boolean,
        default: true,
      },

    },
    data() {
      return {
        searchPerson: '',
        currentTree: [],
        expandedKeys: [],
        selectedKeys: [],
        checkedKeys: [],
        loading:false,
        treeList:[],
      }
    },
    methods: {
      searchTree(tree, keyword, includeChildren = false) {
        const newTree = []
        for (let i = 0; i < tree.length; i++) {
          const node = tree[i];
          if (node[this.fieldNames.title].includes(keyword)) {
            this.expandedKeys.push(node[this.fieldNames.key])
            // 如果当前节点符合条件，则将其复制到新的树形结构中，并根据 includeChildren 参数决定是否将其所有子节点也复制到新的树形结构中
            newTree.push({...node, children: includeChildren ? this.searchTree(node.children || [], '', true) : []})
          } else if (node.children) {
            // 如果当前节点不符合条件且存在子节点，则递归遍历子节点，以继续搜索
            const result = this.searchTree(node.children, keyword, true)
            if (result.length > 0) {
              // 如果子节点中存在符合条件的节点，则将其复制到新的树形结构中
              this.expandedKeys.push(node[this.fieldNames.key])
              newTree.push({...node, children: result})
            }
          }
        }
        return newTree
      },
      searchInit() {
        this.expandedKeys = [];
        this.currentTree = this.searchTree(this.treeList, this.searchPerson, true)
      },
     onSelect(selectedKeys, info) {
       this.$emit("onSelect", this.selectedKeys)
        console.log("---------", this.selectedKeys)
      },

      loadData() {
        if (!this.url) {
          return;
        }
        this.loading = true;
        this.$request({
          url: this.url,
          method: "get",
          data: this.params,
        })
          .then((res) => {
            this.treeList=res.data||[]
            this.currentTree=JSON.parse(JSON.stringify(this.treeList))
            if (this.defaultSelect){
              this.selectedKeys = [res.data[0][this.fieldNames.key]];
              this.$emit("onSelect", this.selectedKeys)
            }
          })
          .finally((res) => {
            this.loading = false;
          });
      },

    },
    mounted() {
      if (this.autoLoad) {
        this.loadData();
      }
    },

  }
</script>

<style lang="less" scoped>
  .lPanelBox {
    height: 100%;
    overflow: auto;
    padding: 0 20px;
    border-right: 1px solid #F7F8F9;
    :deep(.treeBox){
      margin-top: 10px;
    }
  }
  .rPanelBox{
    padding: 0px 20px;
    flex: 1;
  }

</style>

